package wwiii.servlet;

import java.io.IOException;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import o.json.JSONFactory;
import o.json.JSONValue;
import o.json.JSONWriter;
import wwiii.Game;
import wwiii.GameManager;
import wwiii.Player;
import wwiii.PlayerManager;

@SuppressWarnings("serial")
public class GameServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		System.out.println("GameServlet:doGet("+ request.getPathTranslated() +")");

//		resp.setContentType("application/json");
		response.setContentType("text");

		final String thisURL = request.getRequestURI();
		final UserService us = UserServiceFactory.getUserService();
		if (!us.isUserLoggedIn()) {
			response.sendRedirect(us.createLoginURL(thisURL));
			return;
		}
		final User user = us.getCurrentUser();
		user.getUserId();
		user.getNickname();
		user.getEmail();

		final PlayerManager pm = new PlayerManager();
		pm.storePlayer(new Player("id", "mail", "name", 0));

		final GameManager gm = new GameManager();
		final Collection<Game> games = gm.loadGames();

		final JSONFactory factory = new JSONFactory();
		final JSONValue json = factory.create(games);

		final JSONWriter writer = new JSONWriter();
		writer.write(json);

		response.getWriter().write(writer.toString());
	}

	@Override
	protected void doPut(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("GameServlet:doPut("+ req.getPathTranslated() +")");
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("GameServlet:doPost("+ req.getPathTranslated() +")");
	}

	@Override
	protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("GameServlet:doDelete("+ req.getPathTranslated() +")");
	}
}
